import json
from datetime import datetime
import requests
from config import WEATHER_API_KEY, SMS_API_KEY, SMS_API_URL

class MentalTest:
    def __init__(self):
        with open('c:\\Users\\刘佳贺\\Desktop\\软件测试1\\“萤火护心计划”大学生心理暗夜导航工程\\questions.json', 'r', encoding='utf-8') as f:
            self.tests = json.load(f)['tests']

    def select_test(self, age):
        age_group = "儿童" if age < 12 else "青少年" if 12 <= age <= 18 else "青年" if 19 <= age <= 35 else "中年" if 36 <= age <= 59 else "老年"
        print(f"\n{age_group}可选测评量表：")
        
        group_tests = [test for test in self.tests if test.get('age_group') == age_group]
        for i, test in enumerate(group_tests):
            print(f"{i+1}. {test['title']}")
            
        choice = int(input("请选择测评编号：")) - 1
        return group_tests[choice]

    def conduct_test(self, test):
        score = 0
        print(f"\n{test['title']}（共{len(test['questions'])}题）")
        for q in test['questions']:
            print(f"\n{q['text']}")
            print("选项：A.总是 B.经常 C.偶尔 D.从不")
            answer = input("请选择答案（A/B/C/D）：").upper()
            score += q['options'].get(answer, 0)
        return score

    def evaluate_result(self, test, score):
        max_score = sum(max(q['options'].values()) for q in test['questions'])
        severity = score / max_score
        
        print(f"\n您的测评得分：{score}（满分：{max_score}）")
        
        if severity >= 0.75:
            print("评估结果：严重心理困扰，建议立即寻求专业心理咨询或治疗")
        elif severity >= 0.5:
            print("评估结果：中度心理困扰，建议尽快寻求专业帮助")
        elif severity >= 0.25:
            print("评估结果：轻度心理困扰，建议关注心理健康并适当调整")
        else:
            print("评估结果：心理状态良好，继续保持")
            
        if "焦虑" in test['title']:
            print("建议与关怀：尝试深呼吸练习，减少咖啡因摄入，保持规律作息，必要时联系心理咨询师")
        elif "抑郁" in test['title']:
            print("建议与关怀：多与亲友交流，保持适度运动，建立支持系统，必要时寻求专业帮助")
        else:
            print("建议与关怀：请保持规律作息，适量运动，关注情绪变化，必要时联系心理咨询师")

    def get_user_info(self):
        user_info = {}
        user_info['name'] = input("请输入您的姓名：")
        
        while True:
            gender = input("请输入您的性别(男/女)：")
            if gender.strip() in ['男', '女']:
                user_info['gender'] = gender.strip()
                break
            else:
                print("输入错误，性别只能是'男'或'女'，请重新输入")
                continue
                
        user_info['age'] = int(input("请输入您的年龄："))
        while True:
            contact = input("请输入您的联系方式：")
            if len(contact) >= 3 and len(contact) <= 11:
                user_info['contact'] = contact
                break
            else:
                print("联系方式长度应在3-11位之间，请重新输入")
        return user_info
        
    def save_result(self, conn, user_info, test_title, score):
        cursor = conn.cursor()
        cursor.execute('''INSERT INTO users 
                        (name, gender, age, contact, test_time, score, guardian_contact) 
                        VALUES (?, ?, ?, ?, ?, ?, ?)''',
                     (user_info['name'], user_info['gender'], user_info['age'],
                      user_info['contact'], datetime.now(), score, user_info.get('guardian_contact', '')))
        conn.commit()
        
        # 高危人群检测
        if self.is_high_risk_user(user_info, score):
            self.send_alert_email(user_info, score)
            
    def is_high_risk_user(self, user_info, score):
        # 未成年人(小于18岁)、老年人(大于65岁)、孕妇(女性且年龄在18-45岁)
        age = user_info['age']
        is_minor = age < 18
        is_elderly = age > 65
        is_pregnant = user_info['gender'] == '女' and 18 <= age <= 45 and input("您是否怀孕?(y/n): ").lower() == 'y'
        
        # 评分过低(低于30分)或包含危险关键词
        is_low_score = score < 30
        has_suicidal_thoughts = '想死' in input("请描述您最近的感受(可选): ").lower()
        
        return is_minor or is_elderly or is_pregnant or (is_low_score and has_suicidal_thoughts)
        
    def send_alert_email(self, user_info, score):
        try:
            import yagmail
            yag = yagmail.SMTP(
                host='smtp.qq.com',
                user='3031176616@qq.com',
                password='dkpfzgzopeftddie',  # 请确保这是QQ邮箱的授权码而非登录密码
                smtp_ssl=True,
                port=465
            )
            
            subject = '心理健康测评结果SOS'
            content = f"心理健康测评结果\n姓名: {user_info['name']}\n年龄: {user_info['age']}岁\n得分: {score}\n健康状况: 存在高风险，请及时关注!"
            
            yag.send(
                to='3031176616@qq.com',
                subject=subject,
                contents=content
            )
            print("已发送预警邮件至监护人")
        except Exception as e:
            print(f"邮件发送失败: {str(e)}")
            print("请检查: 1. QQ邮箱SMTP服务是否开启 2. 是否使用授权码而非登录密码 3. 网络连接是否正常")